// pages/home/home.js
var app = getApp();
let launchFromQRCode = false;
let loadingWorkTime = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shop1Avatar: "http://www.breakfast-dinner.xin/chb_eatery_images/xingyeyuan_avatar.jpg",
    shop2Avatar: "http://www.breakfast-dinner.xin/chb_eatery_images/daxiuchang_avatar.jpg",
    hereSelected: 0, // 0：未选择，1：堂食，2，打包
    urlEatAtHere: "",
    urlEatAtThere: "",
    home_img_url: null,
    goodsThumb: app.data.global_urls.goodsThumb,
    scrollLeft: 0,
    intervalId: null,
    howToEat: {
      visible: false,
      title: '请选择就餐方式',
      items: [{
          label: '堂食',
        },
        {
          label: '打包',
        }
      ]
    },
    shops:null,
  },

  switchToOrderPage(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  startAutoScroll() {
    const intervalId = setInterval(() => {
      const { scrollLeft, goodsThumb } = this.data;
      const itemWidth = 110; // 每个 item 的宽度加上右边距
      const totalWidth = itemWidth * goodsThumb.length;
      let newScrollLeft = scrollLeft + 2;

      // 检查是否滚动到末尾
      if (newScrollLeft >= totalWidth) {
        newScrollLeft = 0;
      }

      this.setData({
        scrollLeft: newScrollLeft
      });
    }, 20);

    this.setData({
      intervalId
    });
  },

  onScrollToLower() {
    // 当滚动到末尾时，重置滚动位置
    this.setData({
      scrollLeft: 0
    });
  },

  
  switchToHereEat() {
    app.data.globalData.order.unpay.postType = 1;
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  switchToThereEat() {
    app.data.globalData.order.unpay.postType = 2;
    wx.switchTab({
      url: '/pages/index/index',
    })
  },


  onScroll(e){

    this.setData({
      scrollLeft: e.detail.scrollLeft
    })
  },

  previewShop1Avatar(res){
    let shopId = res.currentTarget.dataset.shop;
    let url='';
    if(1 === shopId){
      url = this.data.shop1Avatar;
    }else if(2 === shopId){
      url = this.data.shop2Avatar;
    }
    wx.previewImage({
      // 当前显示图片的链接
      current: this.data.shop1Avatar,
      // 需要预览的图片链接列表
      urls: [url]
    });
  },

  handleSelected(e) {
    var index = e.detail.index;
    app.data.globalData.order.unpay.postType = index+1;
    console.log('就餐方式', app.data.globalData.order.unpay.postType)
    this.setData({
      'howToEat.visible': false
    })
    wx.switchTab({
      url: '/pages/index/index',
    })
    // 2. get all goods list
    app.getAllGoodsList();
  },

  xingyeyuanSelected(){
    if(launchFromQRCode){
      // 二维码启动，这里不选择
      return;
    }
    console.log('兴业园被选择')
    app.data.shops.index = 1;
    this.setData({
      'howToEat.visible': true
    })
    
    // 2. get all goods list
    app.getAllGoodsList();
  },
  daxiuchangSelected(){
    return; // 屏蔽大修厂
    if(launchFromQRCode){
      // 二维码启动，这里不选择
      return;
    }
    console.log('大修厂被选择')
    app.data.shops.index = 2;
    this.setData({
      'howToEat.visible': true
    })
    
    // 2. get all goods list
    app.getAllGoodsList();
  },

  handleActinSheetCancel(){
    this.setData({
      'howToEat.visible': false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取位置
    // 开始自动滚动
    if(options.scene){
      launchFromQRCode = true;
      const scene = decodeURIComponent(options.scene)
      const match = scene.match(/=(\d+)/);
      const shopId = match? Number(match[1]) : 0;
      app.data.shops.index = shopId;
      console.log('-------home: 加载参数-------', shopId, options)
    }else{
      launchFromQRCode = false;
    }
    this.startAutoScroll();
    this.setData({
      shops: app.data.shops
    })

    this.loadWorkTime();
  },

  loadWorkTime(){
    if(loadingWorkTime)
      return;
    
    var that = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    })
    
    wx.request({
      url: app.data.global_urls.getShopsUrl(),
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: null,
      success(res){
        if(res.data && res.data.status === 10000
          && res.data.data){
            that.setData({
              'shops.shopsDetails': res.data.data
            })
          }
        console.log("看看是否同一对象", app.data.shops, app.data.shops.shopsDetails == that.data.shops.shopsDetails)
      },
      complete(e){
        loadingWorkTime = false;
        wx.hideToast();

        const now = new Date();
        // 获取当前小时数
        const currentHour = now.getHours();
        const currentMin = now.getMinutes();
        that.data.shops.shopsDetails.forEach((shop) => {
          if(!shop.startHour){
            return;
          }
          const sHour = shop.startHour;
          const sMin = shop.startMinute;
          const eHour = shop.endHour;
          const eMin = shop.endMinute;
          if((currentHour*60+currentMin < sHour*60+sMin) ||
              (currentHour*60+currentMin > eHour*60+eMin)){
            shop.workStatus = 0;
          }
        })
        
        that.setData({
          shops: that.data.shops
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    
    this.setData({
      urlEatAtHere: app.data.global_urls.urlEatAtHere,
      urlEatAtThere: app.data.global_urls.urlEatAtThere,
      home_img_url: app.data.global_urls.home_url
    })

    this.loadWorkTime();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除定时器
    clearInterval(this.data.intervalId);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})